<?php

header('Content-Type: text/plain');

require_once 'Log.class.php';

$log = Log::instance();
$log->open("mylog.log", LogLevel::$TRACE);

$commandMapping = array(
	'topics' => 'TopicsResource',
	'users' => 'UserResources'
);



$rawRequestUri = $_SERVER['REQUEST_URI']; // eg: "/~foo/PhpDev/JsugVotingRestBackend/?/users"
$key = '/JsugVotingRestBackend/?'; // FIXME hack di hack
$requestPart = substr($rawRequestUri, strpos($rawRequestUri, $key) + strlen($key)); // eg: "/users"


$log->debug("requestPart=[$requestPart]");

$requestParts = split('/', substr($requestPart, 1)); // strip of leading slash
#var_dump($requestParts);

if(count($requestParts) === 0) {
	$msg = "request parts.length was 0!";// TODO request uri was "1" ?!?!!
	echo $msg;
	$log->warn($msg);
	
} else {
	$uriCommand = $requestParts[0]; // extract first part of uri for mapping
	if(isset($commandMapping[$uriCommand]) === false) {
		$msg = 'INVALID uri command ['.$uriCommand.']!'; // TODO
		echo $msg;
		$log->warn($msg);
	} else {
		
		$method = $_SERVER['REQUEST_METHOD'];
		$msg = "URI Command: [" . $uriCommand . "], Method: [".$method."]";
		$log->info($msg);
		
		// $data = $tmp = file_get_contents('php://input');
		
		
		$resourceName = $commandMapping[$uriCommand];
		require_once 'classes/resources/'.$resourceName.'.php';
		$resource = new $resourceName();
		
		if($method == 'GET') {
			$resource->processGet($requestParts);
		} else if($method == 'POST') {
			$resource->processPost($requestParts);
		} else if($method == 'PUT') {
			$resource->processPut($requestParts);
		} else if($method == 'DELETE') {
			$resource->processDelete($requestParts);
		} else {
			$log->warn("Unhandled request method [".$method."]!");
		}
		
		
	}
}

$log->close();

// -----------------------
/*

$urlParts = parse_url($_SERVER['REQUEST_URI']);
$pathParts = split('/', substr($urlParts['path'], 1));

$commandRequest = $pathParts[1];


if(isset($commandMapping[$commandRequest]) === false) {
	die('Invalid command request ['.$commandRequest.']!');
}
$command = $commandMapping[$commandRequest];

if($_SERVER['REQUEST_METHOD'] !== 'GET' &&
   $_SERVER['REQUEST_METHOD'] !== 'POST') {
	// hm....
}
$data = $tmp = file_get_contents('php://input');

#$log->debug($msg);

*/

?>